package com.example.usbhidtool

import android.os.Bundle
import android.util.Log
import android.widget.TextView
import com.example.usbhidtool.utils.StringUtil
import com.example.usbhidtool.utils.TimeUtil
import com.kunminx.architecture.ui.page.DataBindingConfig
import com.socker_server.iowork.ServerIOManager
import com.zhaoliangji.architecture.ui.page.BaseActivity
import java.net.ServerSocket
import java.net.Socket
import java.nio.ByteBuffer
import java.nio.ByteOrder
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors
import kotlin.experimental.and

class SocketServerPage : BaseActivity() {

    lateinit var mState: SocketServerViewModel

    lateinit var mTvLog: TextView

    companion object {
        val IP = "127.0.0.1"
        val PORT = 5001
    }

    private var mExecutorService: ExecutorService? = null
    private var launchService: ExecutorService? = null
    private var mService: Service? = null

    override fun initViewModel() {
        mState = getActivityScopeViewModel(SocketServerViewModel::class.java)
    }

    override fun getDataBindingConfig(): DataBindingConfig {
        return DataBindingConfig(R.layout.activity_socket_server_page, BR.vm, mState)
                .addBindingParam(BR.clickListener, ClickProxy())
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mTvLog = findViewById(R.id.tv_log)
    }


    private fun startListen() {
        mExecutorService = Executors.newCachedThreadPool()
        launchService = Executors.newFixedThreadPool(1)
        launchService?.execute(Runnable { initSocket() })
    }

    private fun initSocket() {
        try {
            val server = ServerSocket(PORT)
//            initConfig() // 配置信息
            updateUILog("端口" + PORT + "server is running")
            var client: Socket?
            while (true) {
                client = server.accept()
                mService = Service(client)
                mExecutorService!!.execute(mService)
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

//    private fun initConfig() {
//        // 默认的消息协议
//        ServerConfig.getInstance().messageProtocol = DefaultMessageProtocol()
//    }

    inner class Service(val socket: Socket) : Runnable {
        var serverIoManager: ServerIOManager? = null

        override fun run() {
            serverIoManager = ServerIOManager(socket)
            serverIoManager!!.startIO()
        }

        fun setMessage(data: ByteArray) {
            updateUILog("sendBuffer:size=" + data.size)
            serverIoManager!!.sendBuffer(data)

        }

        init {
            updateUILog("connect to server :" + socket.inetAddress.hostAddress)
        }
    }

    /**
     * 服务端消息打包
     * 前面4个字节，存放body的长度
     * 后面跟着存放body
     */
    fun msgPack(body: ByteArray): ByteArray {
        val bb = ByteBuffer.allocate(4 + body.size)
        bb.order(ByteOrder.LITTLE_ENDIAN)
        bb.putInt(body.size)
        bb.put(body)
        return bb.array()
    }

    inner class ClickProxy {

        fun clickStartListen() {
            startListen()
            updateUILog("点击开启监听")
        }

        fun clickStopListen() {
//            mService?.setMessage("msg from server".toByteArray())
        }

        /**
         * 发送开始数据测试
         */
        fun clickSentStart() {
            updateUILog("发送开始")
            val msg1 = "开始"
            val msg2 = "1111回传数据123回传数据123回传数据123回传数" +
                    "据123回传数据123回传数据123回传数据123回传数据123回" +
                    "传数据123回传数据123回传数据123回传数据123回传数据123" +
                    "回传数据123回传数据123回传数据123回" +
                    "回传数据123回传数据123回传数据2222回传数据123回传数据123回传数据2222" +
                    "回传数据123回传数据123回传数据2222回传数据123回传数据123回传数据2222" +
                    "回传数据123回传数据123回传数据2222回传数据123回传数据123回传数据3333"
            val barray = msgPack(msg2.encodeToByteArray())
            val hexStr = StringUtil.byteToHex(barray)
            mService?.setMessage(msgPack(msg1.encodeToByteArray()))
            updateUILog("body_size2:" + (msg2.encodeToByteArray().size))
            mService?.setMessage(msgPack(msg2.encodeToByteArray()))
        }

        /**
         * 发送回传数据测试
         */
        fun clickSendData() {
            updateUILog("发送回传数据")
            mService?.setMessage(msgPack("这是回传数据".toByteArray()))
        }


        fun clickClear() {
            showShortToast("清空日志")
            mTvLog.text = ""
        }
    }


    //打印一条日志
    /**
     * @param isSend 是否是发送
     */
    fun updateUILog(log: String, isSend: Boolean = true) {
//        if (log.contains("SOCKET").not()) return
        val dir = if (isSend) "=>" else "<="
        val timeStr = TimeUtil.getHMSFormat(System.currentTimeMillis())
        val str = "[$timeStr]$dir$log\n"
        Log.e(TAG, str)
        runOnUiThread {
            mTvLog.append(str)
        }
    }

}